package com.vinaprime.primeschedule.presentation;

import java.io.IOException;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ProgressBar;

import com.vinaprime.primeschedule.businesslayer.DatabaseController_BL;
import com.vinaprime.primeschedule.presentation.util.SystemUiHider;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class LoaderActivity extends Activity {
	
	protected static final int TIMER_RUNTIME = 300;
    private int mProgressStatus;
    private ProgressBar mProgress;
    ApplicationInformation myAppInfo;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_loader);
		//Set up the action bar to show a dropdown list.
	    final ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    myAppInfo = new ApplicationInformation(getApplicationContext());
	    
		//Add shortcut
	    //addShortcut();
		//Loading....
        mProgress = (ProgressBar)findViewById(R.id.loading);
	     // Start lengthy operation in a background thread
  	        new Thread(new Runnable() {
	            public void run() {
	                 try {
	                        int mProgressStatus = 1;
	                        while (mProgressStatus < TIMER_RUNTIME) {
	                        	 Thread.sleep(1);
	                            	mProgressStatus += 1;
	                                updateProgress(mProgressStatus);
	                           
	                        }
	                } catch(Exception e) {
	                    // do nothing
	                } finally {
	                    //when finish progress bar
	                	onContinue();
	                }
	              }
	            
	        }).start();
  	    
        try {
			Load_Database(this);
			
			myAppInfo.preparePath();
			
			if(!isPrimeScheduleServiceRunning()){
				new Thread(new Runnable() {
					Context context = getApplicationContext();
					public void run() {
						Intent pushIntent = new Intent(context, PrimeScheduleService.class);  
						context.startService(pushIntent);
					}
				}).start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		
	}	


	@Override
	public void onDestroy() {
	    super.onDestroy();
	}
	@Override
	public void onStop() {
	    super.onStop();
	}

	public void updateProgress(int timePassed) {
	    if(null != mProgress) {
	        // Ignore rounding error here
	        final int progress = mProgress.getMax() * timePassed / TIMER_RUNTIME;
	        mProgress.setProgress(progress);
	   }
	}


	public void onContinue() {
		//TO DO IN FINAL
		this.finish();//finish current activity
		Intent intent = new Intent(this, MainActivity.class);
    	startActivity(intent);
	}
	
	public void Load_Database(LoaderActivity loaderActivity) throws IOException
	{	
		String path = myAppInfo.getDBPath();
		
		DatabaseController_BL db = new DatabaseController_BL(getApplicationContext(), path  + "databases/");
		
		if(!db.checkDatabaseExist())
			db.copyDatabase();
		
		//System.out.println("Database Loaded!");
	}
	
	private void addShortcut() {
	    //Adding shortcut for MainActivity
	    //on Home screen
	    Intent shortcutIntent = new Intent(getApplicationContext(),
	    		LoaderActivity.class);
	     
	    shortcutIntent.setAction(Intent.ACTION_MAIN);
	 
	    Intent addIntent = new Intent();
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "PrimeSchedule");
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
	    		Intent.ShortcutIconResource.fromContext(getApplicationContext(),
	                    R.raw.logo_prime));
	 
	    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
	    getApplicationContext().sendBroadcast(addIntent);
	}
	private void removeShortcut() {
	     
	    //Deleting shortcut for MainActivity
	    //on Home screen
	    Intent shortcutIntent = new Intent(getApplicationContext(),
	            LoaderActivity.class);
	    shortcutIntent.setAction(Intent.ACTION_MAIN);
	     
	    Intent addIntent = new Intent();
	    addIntent
	            .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");
	 
	    addIntent
	            .setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
	    getApplicationContext().sendBroadcast(addIntent);
	}
	
	private boolean isPrimeScheduleServiceRunning() {
	    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (PrimeScheduleService.class.getName().equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}
}
